package com.dongjiantong.app.controller.farmrecords;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongjiantong.common.exceptions.HttpCode;
import com.dongjiantong.common.exceptions.OPServerException;
import com.dongjiantong.common.model.Response;
import com.dongjiantong.common.web.sso.LoginInfo;
import com.dongjiantong.common.web.util.UserUtil;
import com.dongjiantong.farmrecords.enums.FarmRecordsFileEnum;
import com.dongjiantong.farmrecords.enums.FarmRecordsNumberStatus;
import com.dongjiantong.farmrecords.model.FarmRecordsDiagnosis;
import com.dongjiantong.farmrecords.model.FarmRecordsFile;
import com.dongjiantong.farmrecords.service.FarmRecordsDiagnosisService;
import com.dongjiantong.farmrecords.service.FarmRecordsFileService;
import com.dongjiantong.openplatform.annotations.OpenBean;
import com.dongjiantong.openplatform.annotations.OpenMethod;
import com.dongjiantong.sys.enums.AnimalTypeEnum;
import com.dongjiantong.sys.service.AnimalTypeService;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 防疫中心-诊疗记录(养殖端)
 */

@Slf4j
@OpenBean
public class FarmRecordsDiagnosisController {

    @Reference(version = "1.0.0")
    public FarmRecordsDiagnosisService farmRecordsDiagnosisService;
    @Reference(version = "1.0.3")
    public AnimalTypeService animalTypeService;

    @Reference(version = "1.0.0")
    public FarmRecordsFileService farmRecordsFileService;

    /**
     * 政府端
     * 根据养殖场id,起止时间或者状态查询诊疗记录 (条件都可以为空,表示查询所有)
     * @param farmId  请求的养殖场id
     * @param fromDate 请求的查询开始时间
     * @param toDate   请求的查询结束时间
     * @param pageNum
     * @param pageSize
     * @return  Response<PageInfo<FarmRecordsDiagnosis>>
     */
    @OpenMethod(key = "app.farmrecords.farmrecordsdiagnosis.selectByFarmIdAndDate",
            paramNames = {"farmId","fromDate","toDate","pageNum","pageSize","breedSecondType"},
            httpMethods = RequestMethod.GET)
    public Response<PageInfo<FarmRecordsDiagnosis>> selectByFarmIdAndDate(
                                                                          @RequestParam(required = false) Long farmId,
                                                                          @RequestParam(required = false) String fromDate,
                                                                          @RequestParam(required = false) String toDate,
                                                                          @RequestParam(required = false) Integer pageNum,
                                                                          @RequestParam(required = false) Integer pageSize,
                                                                          @RequestParam(required = false) Integer breedSecondType){
        if (animalTypeService == null){
            throw new OPServerException("animalTypeService 服务为空,请检查");
        }
        if (farmRecordsDiagnosisService == null){
            throw new OPServerException("请检查 farmRecordsDiagnosisService 服务");
        }
        Map map = Maps.newHashMap();
        Long userId = UserUtil.getUserId();
        map.put("userId",userId);
        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSize == null) {
            pageSize = 20;
        }

        if (farmId != null){
            //如果养殖场id不为空,则根据养殖场id查询
            map.put("farm_id",farmId);
        }

        map.put("status", FarmRecordsNumberStatus.SUBMIT.getCode());

        map.put("animal_second_non_bull",AnimalTypeEnum.BULL.getCode());

        if (breedSecondType != null){
            map.put("breed_second_type",breedSecondType);
        }

        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            if (!Strings.isNullOrEmpty(fromDate)){
                Date startDate = sdf.parse(fromDate);
                map.put("startDate",startDate);
            }
            if (!Strings.isNullOrEmpty(toDate)){
                Date endDate = sdf.parse(toDate);
                map.put("endDate",endDate);
            }

            PageInfo<FarmRecordsDiagnosis> farmRecordsDiagnosisPageInfo = farmRecordsDiagnosisService.selectByMap(pageNum,pageSize,map);

            return Response.ok(farmRecordsDiagnosisPageInfo);

        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
            throw new OPServerException(HttpCode.INTERNAL_SERVER_ERROR,HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    /**
     * 养殖端
     * 根据提交状态分页查询列表
     * @param farmId
     * @param status
     * @return
     */
    @OpenMethod(key = "app.farmrecords.farmrecordsdiagnosis.selectListByStatus",
            paramNames = {"farmId","status","pageSize","pageNum"},
            httpMethods = RequestMethod.GET)
    public Response<PageInfo<FarmRecordsDiagnosis>> selectListByStatus(@RequestParam(required = false) Long farmId,
                                                                        @RequestParam(required = false) Integer status,
                                                                        @RequestParam(required = false) Integer pageSize,
                                                                        @RequestParam(required = false) Integer pageNum){
        if (farmRecordsDiagnosisService == null){
            throw new OPServerException("farmRecordsDiagnosisService 服务为空,请重启服务后重试");
        }
        if (farmId == null){
            throw new OPServerException("养殖场id不能为空,请检查后重试");
        }

        if (pageSize == null){
            pageSize = 20;
        }
        if (pageNum == null){
            pageNum = 1;
        }

        //这里查询除牛之外的其他动物
        Integer nonBull = AnimalTypeEnum.BULL.getCode();

        try {
            PageInfo<FarmRecordsDiagnosis> productionPageInfo = farmRecordsDiagnosisService.selectListByStatus(pageNum,pageSize,status,farmId,nonBull);

            return Response.ok(productionPageInfo);
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
            throw new OPServerException(HttpCode.INTERNAL_SERVER_ERROR,HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    /**
     * 根据主键id查询对应诊疗记录
     * @param id
     * @return  Response<FarmRecordsDiagnosis>
     */
    @OpenMethod(key = "app.farmrecords.farmrecordsdiagnosis.selectById",
            paramNames = {"id"},
            httpMethods = RequestMethod.GET)
    public Response<FarmRecordsDiagnosis> selectById(@RequestParam(required = false)Long id){
        if (id == null) {
            throw new OPServerException(HttpCode.BAD_REQUEST,"请求id不能为空");
        }
        try {
            if (farmRecordsDiagnosisService == null){
                throw new OPServerException("farmRecordsDiagnosisService 为null,请检查");
            }
            FarmRecordsDiagnosis farmRecordsDiagnosis= farmRecordsDiagnosisService.selectByPrimaryKey(id);

            List<FarmRecordsFile> farmRecordsFileList = farmRecordsFileService.selectPicOrVideoListByRelevanceIds(Lists.newArrayList(farmRecordsDiagnosis.getId()), FarmRecordsFileEnum.DIAGNOSIS.getCode(),Lists.newArrayList(FarmRecordsFileEnum.VIDEO.getCode(),FarmRecordsFileEnum.PHOTO.getCode()));

            //放入图片 视频到对象中
            FarmRecordsDiagnosis farmRecordsDiagnosis1 = farmRecordsDiagnosisService.setPicOrVideoByObject(farmRecordsDiagnosis,farmRecordsFileList);

            if (farmRecordsDiagnosis1 == null){
                return Response.fail(HttpCode.INTERNAL_SERVER_ERROR,"查无数据");
            }
            return Response.ok(farmRecordsDiagnosis1);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new OPServerException(HttpCode.INTERNAL_SERVER_ERROR,"数据查询发生异常,请稍后重试");
        }
    }

    /**
     * 新增一条诊疗记录 (直接暂存 或者 直接提交)
     * @param farmRecordsDiagnosis
     * @param toStatus 单据改变为状态
     * @return long 返回插入数据的id
     */
    @OpenMethod(key = "app.farmrecords.farmrecordsdiagnosis.createOne",
                            paramNames = {"farmRecordsDiagnosis","toStatus"},
                            httpMethods = RequestMethod.POST)
    public Response<Map<String,Object>> createOne(@RequestBody(required = false) FarmRecordsDiagnosis farmRecordsDiagnosis,
                                    @RequestParam(required = false) Integer toStatus){
        if (farmRecordsDiagnosis == null) {
            throw new OPServerException(HttpCode.BAD_REQUEST,"请求参数对象不能为空");
        }
        if (farmRecordsDiagnosisService == null){
            throw new OPServerException("farmRecordsDiagnosisService 为null,请检查");
        }

        LoginInfo loginInfo = UserUtil.getCurrentUser();

        Long id = farmRecordsDiagnosisService.createOne(loginInfo,farmRecordsDiagnosis, toStatus);

        Map<String,Object> result =  Maps.newHashMap();
        result.put("receiptId",id);

        return Response.ok(result);
    }

    /**
     * 根据id或者number 更新一条单据信息
     * @param farmRecordsDiagnosis 请求的对象
     * @return  boolean (更新成功返回true 反之返回false)
     */
    @OpenMethod(key = "app.farmrecords.farmrecordsdiagnosis.updateByIdOrNumber",
            paramNames = {"farmRecordsDiagnosis","toStatus"},
            httpMethods = RequestMethod.POST)
    public Response<Object> updateByIdOrNumber(@RequestBody (required = false) FarmRecordsDiagnosis farmRecordsDiagnosis,
                                                @RequestParam(required = false) Integer toStatus){
        if (farmRecordsDiagnosis == null){
            throw new OPServerException(HttpCode.BAD_REQUEST,"请求参数对象不能为空");
        }else{
            if (farmRecordsDiagnosisService == null){
                throw new OPServerException("farmRecordsDiagnosisService 为null,请检查");
            }
            if (farmRecordsDiagnosis.getId() == null){
                throw new OPServerException(HttpCode.PRIMARY_KEY_ID_IS_NOT_EXIST,HttpCode.PRIMARY_KEY_ID_IS_NOT_EXIST.getMessage());
            }else {
                Integer con = farmRecordsDiagnosisService.updateByIdOrNumber(farmRecordsDiagnosis,toStatus);

                Map<String,Object> map = Maps.newHashMap();
                if (con == 1) {
                    map.put("updateResult","true");
                }else {
                    map.put("updateResult","false");
                }

                return Response.ok(map);
            }
        }
    }
}
